<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\common\services;


use app\common\model\addonAuth\AddonGroup;
use app\common\model\platform\Platform;
use app\common\model\user\UserPermission;
use think\App;

class User
{
    public $user_addons = [];
    public $default_group_addons = [];
    public $user_permission_addons = [];

    /**
     * @var AddonGroup
     */
    private $AddonGroup;


    public function __construct()
    {
        $this->AddonGroup = new AddonGroup();
    }

    /**
     * 获取用户可用的所有应用以及权限
     * @param $uid
     * @return array
     */
    public function getUserAllAddons($uid, $plaid=0)
    {
        $plaid = $plaid ?: get_plaid();
        $platform = (new Platform())->where(['plaid' => $plaid, 'uid' => $uid])->count();
        if ($platform) {
            $this->getDefaultGroupAddons($uid); //默认组
        }
        //子账号
        $this->getPermissionAddons($uid);
        return $this->mergeAddons($this->default_group_addons,  $this->user_addons, $this->user_permission_addons);
    }

    /**
     * 获取默认的应用组应用
     * @param $uid
     * @return array|mixed
     */
    public function getDefaultGroupAddons($uid)
    {
        $User = new \app\common\model\user\User();
        $user = $User->where(['uid' => $uid])->find();
        $addon_group_id = $user->addon_group_id;
        if ($addon_group_id != 0) {
            $user_group = $this->AddonGroup->where(['id' => $addon_group_id])->find();
        } else {
            $user_group = $this->AddonGroup->where(['default' => 1])->find();
        }
        $this->user_addons = $user->addons_auth??[];
        if ($user_group) {
            $this->default_group_addons = $user_group->addons;
            return $this->default_group_addons;
        }
        return [];
    }

    /**
     * 子账号的应用组权限
     * @param $uid
     * @return array|mixed
     */
    public function getPermissionAddons($uid)
    {
        $this->user_permission_addons = (new UserPermission())->getAddonAllAuth($uid);
        return $this->user_permission_addons;
    }

    /**
     * 合并应用权限
     * @param mixed ...$addons
     * @return array
     */
    public function mergeAddons(...$addons)
    {
        $res = [];
        foreach ($addons as $key => $value) {
            $value = $value ?? [];
            foreach ($value as $addon_name => $auth) {
                if (!isset($res[$addon_name])) {
                    $res[$addon_name] = [];
                }
                $res[$addon_name] = array_unique(array_merge($res[$addon_name], $auth));
                if (in_array('all', $res[$addon_name])) {
                    $res[$addon_name] = ['all'];
                }
            }
        }
        return $res;
    }
}
